﻿using IOP.Protocols.MQTT;
using IOP.Protocols.MQTT.Package;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;

namespace IOP.Pulsar.MQTT.Abstractions
{
    /// <summary>
    /// 主题
    /// </summary>
    public class Topic
    {
        /// <summary>
        /// 主题名
        /// </summary>
        public string TopicName { get; set; }
        /// <summary>
        /// 缓存数据
        /// </summary>
        public ConcurrentBag<CachePackage> Datas { get; set; } = new ConcurrentBag<CachePackage>();
        /// <summary>
        /// 当当前主题接收到发布数据时
        /// </summary>
        public event Action<PublishPackage> OnPublish;
        /// <summary>
        /// 当缓存数据发生变更时
        /// </summary>
        public event Action<string, ConcurrentBag<CachePackage>> OnCacheChanged;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="name"></param>
        public Topic(string name)
        {
            TopicName = name;
        }
        /// <summary>
        /// 发布消息
        /// </summary>
        /// <param name="package"></param>
        public void Publish(PublishPackage package)
        {
            if (package.QoS != QoSType.QoS0 && package.RETAIN)
            {
                var packages = new CachePackage() { QoSType = package.QoS, PublishPackage = package };
                Datas.Add(packages);
                OnCacheChanged?.Invoke(TopicName, Datas);
            }
            else if (package.QoS == QoSType.QoS0 && package.RETAIN)
            {
                Datas.Clear();
                var packages = new CachePackage() { QoSType = package.QoS, PublishPackage = package };
                Datas.Add(packages);
                OnCacheChanged?.Invoke(TopicName, Datas);
            }
            OnPublish?.Invoke(package);
        }
    }
}
